<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xizhongren8980/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xizhongren8980/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xizhongren8980/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xizhongren8980/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xizhongren8980/css/main.css">


<link rel="stylesheet" href="/xizhongren8980/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xizhongren8980/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="题目描述：给你一个整数数组 nums 和一个整数 k。 如果某个 连续 子数组中恰好有 k 个奇数数字，我们就认为这个子数组是「优美子数组」。">
<meta property="og:type" content="article">
<meta property="og:title" content="【LeetCode】1248题之统计[优美子数组]">
<meta property="og:url" content="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/04/21/1248%E9%A2%98%E4%B9%8B%E7%BB%9F%E8%AE%A1[%E4%BC%98%E7%BE%8E%E5%AD%90%E6%95%B0%E7%BB%84]/index.html">
<meta property="og:site_name" content="一杯茶一包烟，一个BUG改一天">
<meta property="og:description" content="题目描述：给你一个整数数组 nums 和一个整数 k。 如果某个 连续 子数组中恰好有 k 个奇数数字，我们就认为这个子数组是「优美子数组」。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/xizhongren8980/Hexo_src/raw/master/LeetCode/1248_1.png">
<meta property="og:image" content="https://gitee.com/xizhongren8980/Hexo_src/raw/master/LeetCode/1248_result.png">
<meta property="article:published_time" content="2020-04-21T14:43:23.873Z">
<meta property="article:modified_time" content="2020-04-28T06:34:26.209Z">
<meta property="article:author" content="MisterTian">
<meta property="article:tag" content="数组">
<meta property="article:tag" content="边界处理">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/xizhongren8980/Hexo_src/raw/master/LeetCode/1248_1.png">

<link rel="canonical" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/04/21/1248%E9%A2%98%E4%B9%8B%E7%BB%9F%E8%AE%A1[%E4%BC%98%E7%BE%8E%E5%AD%90%E6%95%B0%E7%BB%84]/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>【LeetCode】1248题之统计[优美子数组] | 一杯茶一包烟，一个BUG改一天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xizhongren8980/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一杯茶一包烟，一个BUG改一天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">收藏永不停止，学习永不开始</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xizhongren8980/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/xizhongren8980/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xizhongren8980/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xizhongren8980/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xizhongren8980/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/04/21/1248%E9%A2%98%E4%B9%8B%E7%BB%9F%E8%AE%A1[%E4%BC%98%E7%BE%8E%E5%AD%90%E6%95%B0%E7%BB%84]/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xizhongren8980/images/head.jpg">
      <meta itemprop="name" content="MisterTian">
      <meta itemprop="description" content="一个小菜鸟">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一杯茶一包烟，一个BUG改一天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          【LeetCode】1248题之统计[优美子数组]
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-21 22:43:23" itemprop="dateCreated datePublished" datetime="2020-04-21T22:43:23+08:00">2020-04-21</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-04-28 14:34:26" itemprop="dateModified" datetime="2020-04-28T14:34:26+08:00">2020-04-28</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/xizhongren8980/categories/LeetCode/" itemprop="url" rel="index"><span itemprop="name">LeetCode</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="题目描述："><a href="#题目描述：" class="headerlink" title="题目描述："></a>题目描述：</h4><p>给你一个整数数组 <code>nums</code> 和一个整数 <code>k</code>。</p>
<p>如果某个 连续 子数组中恰好有 k 个奇数数字，我们就认为这个子数组是「优美子数组」。<a id="more"></a></p>
<p>请返回这个数组中「优美子数组」的数目。</p>
<h4 id="示例："><a href="#示例：" class="headerlink" title="示例："></a>示例：</h4><pre>
输入：nums = [1,1,2,1,1], k = 3
输出：2
解释：包含 3 个奇数的子数组是 [1,1,2,1] 和 [1,2,1,1] 
</pre>

<pre>
输入：nums = [2,2,2,1,2,2,1,2,2,2], k = 2
输出：16
</pre>


<h4 id="分析："><a href="#分析：" class="headerlink" title="分析："></a>分析：</h4><p>这个题的主要难点在于要理解[优美子数组]的计算方法，我们可以新建一个<code>oddArray</code>数组用来存储nums数组中奇数的下标，利用<code>oddArray</code>数组就可以方便遍历找出k个奇数的组合。</p>
<p>以数组<code>1 2 2 3 3 3 8</code>举例计算优美子数组：</p>
<p><img src="https://gitee.com/xizhongren8980/Hexo_src/raw/master/LeetCode/1248_1.png" alt=""></p>
<p>计算方法：</p>
<ol>
<li><p>首先计算出oddArray数组，即把奇数的坐标作为oddArray数组中的的元素值；</p>
</li>
<li><p>对oddArray数组进行遍历，每次找到相邻的k个元素；</p>
</li>
<li><p>以这k个元素的值作为下标对应到nums数组找出这k个奇数；</p>
</li>
<li><p>在nums数组中找出只含这k个奇数的子数组，计算方法为以这k个元素为中心，分别计算出其左边和右边的非奇数的个数，假设为<code>left_num</code>,<code>right_num</code>。那么在nums数组中只含这k个奇数的数组就是<code>（(left_num * right_num) + left_num + right_num）</code>，合并表达式即为<code>（(left_num + 1)*(right_num+ 1)）</code></p>
</li>
<li><p>重复步骤2 3 4，直到列举出所有k个奇数的组合。</p>
</li>
</ol>
<p>找出计算的方法后就可以着手编码实现了，但是在编码的过程中，使用上述方法计算时无法避免处于边界值的判断，这时就要分多种情况讨论，例如左边或者右边处于边界值，无法简单地通过遍历<code>oddArray</code>数组的下标减一或者加一进行计算；</p>
<p>为了解决此问题，我们可以对<code>oddArray</code>数组作简单改进，令<code>oddArray</code>数组第一个元素为-1，最后一个元素为nums数组的长度，这样就恰好解决边界值的判断问题。 </p>
<h4 id="Java实现"><a href="#Java实现" class="headerlink" title="Java实现"></a>Java实现</h4><figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">&lt;pre&gt;</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Solution</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="built_in">int</span> numberOfSubarrays(<span class="built_in">int</span>[] nums, <span class="built_in">int</span> k) &#123;</span><br><span class="line">        ArrayList&lt;Integer&gt; oddList = new ArrayList&lt;&gt;();     <span class="comment">//记录奇数元素的下标</span></span><br><span class="line">        oddList.add(<span class="number">-1</span>);    <span class="comment">// 最开始的元素为-1，方便计算边界值，减少判断</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="built_in">int</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (nums[i] % <span class="number">2</span> != <span class="number">0</span>) &#123;</span><br><span class="line">                oddList.add(i);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        oddList.add(nums.length);   <span class="comment">//最后的元素为数组长度，便于计算边界值</span></span><br><span class="line">        <span class="built_in">int</span> result = <span class="number">0</span>; <span class="comment">//记录奇数数组的数量</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(<span class="built_in">int</span> j = <span class="number">1</span>;  j + k &lt; oddList.size(); j++)&#123;</span><br><span class="line">            result += (oddList.<span class="keyword">get</span>(j) - oddList.<span class="keyword">get</span>(j - <span class="number">1</span>)) * (oddList.<span class="keyword">get</span>(j + k) - oddList.<span class="keyword">get</span>(j + k - <span class="number">1</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">&lt;/pre&gt;</span><br></pre></td></tr></table></figure>

<h4 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h4><p><img src="https://gitee.com/xizhongren8980/Hexo_src/raw/master/LeetCode/1248_result.png" alt=""></p>
<h4 id="优化"><a href="#优化" class="headerlink" title="优化"></a>优化</h4><p>将记录奇数元素下标的链表改为用数组可以有效减少运行的时间。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xizhongren8980/tags/%E6%95%B0%E7%BB%84/" rel="tag"># 数组</a>
              <a href="/xizhongren8980/tags/%E8%BE%B9%E7%95%8C%E5%A4%84%E7%90%86/" rel="tag"># 边界处理</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/04/20/200%E9%A2%98%E4%B9%8B%E5%B2%9B%E5%B1%BF%E6%95%B0%E9%87%8F/" rel="prev" title="【LeetCode】200题之岛屿数量">
      <i class="fa fa-chevron-left"></i> 【LeetCode】200题之岛屿数量
    </a></div>
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/04/22/199%E9%A2%98%E4%B9%8B%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%8F%B3%E8%A7%86%E5%9B%BE/" rel="next" title="【LeetCode】199题之二叉树的右视图">
      【LeetCode】199题之二叉树的右视图 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#题目描述："><span class="nav-number">1.</span> <span class="nav-text">题目描述：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#示例："><span class="nav-number">2.</span> <span class="nav-text">示例：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#分析："><span class="nav-number">3.</span> <span class="nav-text">分析：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Java实现"><span class="nav-number">4.</span> <span class="nav-text">Java实现</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#运行结果"><span class="nav-number">5.</span> <span class="nav-text">运行结果</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#优化"><span class="nav-number">6.</span> <span class="nav-text">优化</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="MisterTian"
      src="/xizhongren8980/images/head.jpg">
  <p class="site-author-name" itemprop="name">MisterTian</p>
  <div class="site-description" itemprop="description">一个小菜鸟</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xizhongren8980/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/xizhongren8980/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/xizhongren8980/tags/">
          
        <span class="site-state-item-count">101</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://mistertian8980.github.io/" title="https:&#x2F;&#x2F;mistertian8980.github.io&#x2F;" rel="noopener" target="_blank">Github博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MisterTian</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/xizhongren8980/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/xizhongren8980/lib/anime.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.ui.min.js"></script>

<script src="/xizhongren8980/js/utils.js"></script>

<script src="/xizhongren8980/js/motion.js"></script>


<script src="/xizhongren8980/js/schemes/pisces.js"></script>


<script src="/xizhongren8980/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_lines.min.js"></script>


  




  
<script src="/xizhongren8980/js/local-search.js"></script>













  

  

</body>
</html>
